//
//  FSSearchViewController.m
//  WZSOA
//
//  Created by 刘沿 on 16/7/6.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSSearchViewController.h"
#import "GDataDefines.h"

@interface FSSearchViewController ()

@property (nonatomic,assign) NSInteger currentPage;

@property(nonatomic,assign)int totalCounts; //总条数

@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation FSSearchViewController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.currentPage = 1;
    
    [self loadData];
    
    __weak typeof (self) weakSelf = self;

    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            
            [weakSelf loadMore];
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];

}

- (void)loadData{
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSString *condition = self.text;
    
    NSArray * array = @[@{@"condition":condition},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    NSString *method = nil;
    
    NSString *url = nil;
    
    if (self.type == recriveSearch) {
// 收文
        method = KFilesInSearch;
        
        url = KexchSearch;
        
    }else if(self.type == sendSearch){
        
        url = KexchSearch;
        method = KFilesDispatchSearch;
        
    }else {
        url = KexchSearch;
    
        method = KArchiveYearSearch;
    
        array = @[@{@"dbpath":self.debpath},@{@"condition":condition},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
        
    }
    
       [HttpTools postWithURL:url arrays:array method:method success:^(id JSON) {
        
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
//        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"没有数据哦"];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}

- (void)loadMore{

    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSString *condition = self.text;
    
    NSArray * array = @[@{@"condition":condition},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:KexchSearch arrays:array method:KFilesInSearch success:^(id JSON) {
        
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        
//        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"没有数据哦"];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
}


//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel * model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"搜索结果(%d)",self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSReceiveModel * model = self.dataArray[indexPath.row];
    CGFloat height = 0;
    CGFloat  titlesize  = [FSHightTool heightbyString:model.title font:14 minsWidth:60];
    
    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
    CGFloat dessize = [FSHightTool heightbyString:desstring font:13 minsWidth:60];;
    height = titlesize + dessize + 25;
    return  height;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSNewReceiveCell * cell = [FSNewReceiveCell cellWithTableView:tableView];
    FSNewReceiveModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.type == recriveSearch) {
        
        FSNewReceiveModel * model = self.dataArray[indexPath.row];
        
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        FSNewReceiveDetailController *vc = [story instantiateViewControllerWithIdentifier:@"NewDetailReceiveVC"];
        
        vc.type = newReceive;
        
        vc.fileId = model.fileId;
        
        [self.navigationController pushViewController:vc animated:YES];
        

    }else if(self.type == sendSearch){
    
        FSNewReceiveModel * model = self.dataArray[indexPath.row];
        
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        FSNewSendDetailController *sendDEtail = [sb instantiateViewControllerWithIdentifier:@"NewSendDetailVC"];
        
        
        sendDEtail.fileId = model.fileId;
        
        
        [self.navigationController pushViewController:sendDEtail animated:YES];
    
    }else {
    
        FSReceiveModel * model = self.dataArray[indexPath.row];
        
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        FSNewReceiveDetailController *vc = [story instantiateViewControllerWithIdentifier:@"NewDetailReceiveVC"];
        
        vc.type = ProfileSear;
        
        vc.fileId = model.fileId;
        
        vc.dbpath = self.debpath;//[NSString stringWithFormat:@"weboa/files/files%@.nsf",self.lastbtn.titleLabel.text];
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}

@end




















